/**
 *    TimedProfiles - let Android perform tasks based on conditions
 *    Copyright (C) 2011  Daniel Weinhold
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * */
package de.drak.Profiles.plugins;


import android.app.Activity;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.CompoundButton.OnCheckedChangeListener;
import de.drak.Profiles.OnlineHelp;
import de.drak.Profiles.R;
import de.drak.Profiles.TimedProfiles;

/**Edit Volumes for Volume Setting*/
public class VolumeSeter extends Activity {

	private static final int MENU_SAVE = 1;
	private static final int MENU_DONT_SAVE = 2;
	static final String SAVE_VIB_CALL = "vol.vib.call";
	static final String SAVE_VIB_INFO = "vol.vib.info";
	static final String SAVE_VOL = "vol.stream";

	private class Holder {
		CheckBox check;
		SeekBar seek;
	}
	
	static final int[] STREAM_TYPES = {
		AudioManager.STREAM_RING,
		AudioManager.STREAM_NOTIFICATION,
		AudioManager.STREAM_MUSIC,
		AudioManager.STREAM_ALARM,
		AudioManager.STREAM_VOICE_CALL,
		AudioManager.STREAM_SYSTEM
	};
	
	static final char[] STREAM_LETTERS = {
		'R',
		'N',
		'M',
		'A',
		'C',
		'S'
	};
	
	private static final int[] SLIDER_IDS = {
		R.id.Seek_vol_ring, R.id.Seek_vol_info, R.id.Seek_vol_media, R.id.Seek_vol_alarm, R.id.Seek_vol_voice, R.id.Seek_vol_sys  
	};
	
	private static final int[] CHECK_IDS = {
		R.id.Check_vol_ring, R.id.Check_vol_info, R.id.Check_vol_media, R.id.Check_vol_alarm, R.id.Check_vol_voice, R.id.Check_vol_sys  
	};

	private AudioManager mManager;

	/**Indicates if Activity should return RESULT_CANCELED*/
	private boolean isCancelled;
	
	private SeekBar.OnSeekBarChangeListener silderUI = new SeekBar.OnSeekBarChangeListener(){
		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			//not needed
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			//not needed
		}

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			//update text
			//set checkbox
		}
	};
	private OnCheckedChangeListener chcker = new OnCheckedChangeListener(){

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			// TODO Auto-generated method stub
			Holder h = (Holder) buttonView.getTag();
			h.seek.setEnabled(isChecked);
		}
	};	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onCreate(final Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		
		setContentView(R.layout.set_vol);

        //load title
		TimedProfiles.createTitle(this, getString(R.string.plugin_screenset));
		
		
		mManager = (AudioManager) getSystemService(Activity.AUDIO_SERVICE);

		final int size = STREAM_TYPES.length;
		int value, max;
		Holder holder;
		for (int i=0; i<size; i++) {
			
			value = mManager.getStreamVolume(STREAM_TYPES[i]);
			max = mManager.getStreamMaxVolume(STREAM_TYPES[i]);

			holder = new Holder();
			holder.check = (CheckBox) findViewById(CHECK_IDS[i]);
			holder.seek = (SeekBar) findViewById(SLIDER_IDS[i]);
			
			holder.seek.setMax(max);
			//holder.seek.setTag(holder);
			holder.seek.setProgress(value);
			holder.seek.setSecondaryProgress(value);
			holder.seek.setOnSeekBarChangeListener(silderUI);	
			holder.seek.setEnabled(false);
			holder.check.setOnCheckedChangeListener(chcker);
			holder.check.setTag(holder);
			holder.check.setChecked(false);
		}
		((RadioGroup) findViewById(R.id.RadioGroup01)).check(R.id.RadioButton01);
		((RadioGroup) findViewById(R.id.RadioGroup02)).check(R.id.RadioButton01);

	
		

		/*
		 * if savedInstanceState == null, then we are entering the Activity directly and we need to check whether the
		 * Intent has forwarded a Bundle extra (e.g. whether we editing an old condition or creating a new one)
		 */
		if (savedInstanceState == null)
		{
			final Bundle forwardedBundle = getIntent().getBundleExtra(QueryReceiver.INTENT_BUNDLE);

			/*
			 * the forwardedBundle would be null if this was a new condition
			 */
			if (forwardedBundle == null)
			{	
				((CheckBox) findViewById(R.id.CheckBox03)).setChecked(true);
				((CheckBox) findViewById(R.id.CheckBox03)).setVisibility(View.VISIBLE);
				
				
			}else{
				if(getIntent().hasExtra(TimedProfiles.INTENT_BUNDLE_UNSET))
				{
					//there is an unset bundle
					((CheckBox) findViewById(R.id.CheckBox03)).setVisibility(View.VISIBLE);
					((CheckBox) findViewById(R.id.CheckBox03)).setText(R.string.unsetbundle_edit);
				}
				
				//steams
				CheckBox c;
				SeekBar b;
				for (int i=0; i<size; i++) {
					if(!forwardedBundle.containsKey(SAVE_VOL+i))
					{
						continue;
					}

					c = (CheckBox) findViewById(CHECK_IDS[i]);
					b = (SeekBar) findViewById(SLIDER_IDS[i]);
					
					b.setProgress(forwardedBundle.getInt(SAVE_VOL+i));
					b.setEnabled(true);
					c.setChecked(true);
				}
				//vibrate
				if(forwardedBundle.containsKey(SAVE_VIB_INFO))
				{
					((RadioGroup) findViewById(R.id.RadioGroup02)).check(forwardedBundle.getBoolean(SAVE_VIB_INFO)?R.id.RadioButton02:R.id.RadioButton03);
				}
				if(forwardedBundle.containsKey(SAVE_VIB_CALL))
				{
					((RadioGroup) findViewById(R.id.RadioGroup01)).check(forwardedBundle.getBoolean(SAVE_VIB_CALL)?R.id.RadioButton02:R.id.RadioButton03);
				}

			}
		}
		/*
		 * if savedInstanceState != null, there is no need to restore any Activity state directly (e.g. onSaveInstanceState()).
		 * This is handled by the Spinner automatically
		 */
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void finish()
	{
		if (isCancelled)
			setResult(RESULT_CANCELED);
		else
		{

			/*
			 * This is the return Intent, into which we'll put all the required extras
			 */
			final Intent returnIntent = new Intent();

			/*
			 * This extra is the data to ourselves: either for the Activity or the BroadcastReceiver. Note that anything placed in
			 * this Bundle must be available to Locale's class loader. So storing String, int, and other basic objects will work
			 * just fine. You cannot store an object that only exists in your app, as Locale will be unable to serialize it.
			 */
			final Bundle storeAndForwardExtras = new Bundle();

			boolean some_to_save = false;
			StringBuilder statstr = new StringBuilder();
			
			//steams
			final int size = STREAM_TYPES.length;
			SeekBar bar;
			for (int i=0; i<size; i++) {
								
				if(((CheckBox) findViewById(CHECK_IDS[i])).isChecked())
				{
					some_to_save = true;
					
					bar = (SeekBar) findViewById(SLIDER_IDS[i]);
					
					final int p = bar.getProgress();
					
					statstr.append(String.format("%c:%d ", STREAM_LETTERS[i], p));
					
					storeAndForwardExtras.putInt(SAVE_VOL+i, p);
				}
			}
			//vibrate on call
			if(((RadioGroup) findViewById(R.id.RadioGroup01)).getCheckedRadioButtonId()!=R.id.RadioButton01)
			{
				some_to_save = true;
				storeAndForwardExtras.putBoolean(SAVE_VIB_CALL, ((RadioGroup) findViewById(R.id.RadioGroup01)).getCheckedRadioButtonId()==R.id.RadioButton02);
				statstr.append(String.format("R: %s ", storeAndForwardExtras.getBoolean(SAVE_VIB_CALL)?"vib":"no vib"));
			}
			//vibrate on notify
			if(((RadioGroup) findViewById(R.id.RadioGroup02)).getCheckedRadioButtonId()!=R.id.RadioButton01)
			{
				some_to_save = true;
				storeAndForwardExtras.putBoolean(SAVE_VIB_INFO, ((RadioGroup) findViewById(R.id.RadioGroup02)).getCheckedRadioButtonId()==R.id.RadioButton02);
				statstr.append(String.format("N: %s", storeAndForwardExtras.getBoolean(SAVE_VIB_INFO)?"vib":"no vib"));
			}

			if(!some_to_save){
				//nothing
				setResult(TimedProfiles.RESULT_REMOVE);
				super.finish();
				return;
			}
			
			returnIntent.putExtra(TimedProfiles.INTENT_INFO_STR, statstr.toString());
			storeAndForwardExtras.putInt(QueryReceiver.TYPE_FIELD, QueryReceiver.IS_VOL);
			returnIntent.putExtra(QueryReceiver.INTENT_BUNDLE, storeAndForwardExtras);
			
			if(((CheckBox) findViewById(R.id.CheckBox03)).getVisibility()==View.VISIBLE
					&& ((CheckBox) findViewById(R.id.CheckBox03)).isChecked())
			{
				//new instance - unset bundle
				final Bundle endB = new Bundle(),
							caps  = new Bundle();
				
				//get current steams
				for (int i=0; i<size; i++) {
										
					if(((CheckBox) findViewById(CHECK_IDS[i])).isChecked())
					{
						endB.putInt(SAVE_VOL+i, mManager.getStreamVolume(STREAM_TYPES[i]));
					}
				}
				//vibrate on call?
				if(((RadioGroup) findViewById(R.id.RadioGroup01)).getCheckedRadioButtonId()!=R.id.RadioButton01)
				{
					storeAndForwardExtras.putBoolean(SAVE_VIB_CALL, 
							mManager.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER)==AudioManager.VIBRATE_SETTING_ON
							||(mManager.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER)==AudioManager.VIBRATE_SETTING_ONLY_SILENT &&
							   mManager.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE
							)
					);
				}
				//vibrate on notify?
				if(((RadioGroup) findViewById(R.id.RadioGroup02)).getCheckedRadioButtonId()!=R.id.RadioButton01)
				{
					storeAndForwardExtras.putBoolean(SAVE_VIB_INFO, mManager.getVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION)==AudioManager.VIBRATE_SETTING_ON);
				}
				
				endB.putInt(QueryReceiver.TYPE_FIELD, QueryReceiver.IS_VOL);
				
				caps.putString(TimedProfiles.INTENT_INFO_STR, "!"+statstr.toString());
				caps.putBundle(QueryReceiver.INTENT_BUNDLE, endB);
				
				returnIntent.putExtra(TimedProfiles.INTENT_BUNDLE_UNSET, caps);
			}

			setResult(RESULT_OK, returnIntent);
		}

		super.finish();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onCreateOptionsMenu(final Menu menu)
	{
		super.onCreateOptionsMenu(menu);

		final Intent helpIntent = new Intent(this, OnlineHelp.class);
		helpIntent.putExtra("com.twofortyfouram.locale.intent.extra.HELP_URL", OnlineHelp.HELP_URL_PRE+"plugin/VolumeSeter");

		// Note: title set in onCreate
		helpIntent.putExtra(TimedProfiles.INTENT_TITLE, getTitle());

		menu.add(R.string.onlinehelp)
			.setIcon(android.R.drawable.ic_menu_help).setIntent(helpIntent);
		menu.add(0, MENU_DONT_SAVE, 0, android.R.string.cancel)
			.setIcon(android.R.drawable.ic_menu_close_clear_cancel).getItemId();
		menu.add(0, MENU_SAVE, 0, R.string.plugin_save)
			.setIcon(android.R.drawable.ic_menu_save).getItemId();
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onMenuItemSelected(final int featureId, final MenuItem item)
	{
		switch (item.getItemId())
		{
			case MENU_SAVE:
			{
				finish();
				return true;
			}
			case MENU_DONT_SAVE:
			{
				isCancelled = true;
				finish();
				return true;
			}
		}

		return super.onOptionsItemSelected(item);
	}
}